# 查找llvm-config可执行文件，并获得版本号
MIN_SUPPORT_MAJOR_VERSION = 20
MAX_SUPPORT_MAJOR_VERSION = 20
LLVM_CONFIG_BIN =

define find_llvm_config_bin
    $(eval TMP := $(shell which llvm-config$(1) 2>/dev/null))
    $(if $(TMP),$(eval LLVM_CONFIG_BIN := llvm-config$(1)))
endef

ifdef MAJOR_VERSION
	ifneq ($(shell which llvm-config$(MAJOR_VERSION) 2>/dev/null),)
		LLVM_CONFIG_BIN = llvm-config$(MAJOR_VERSION)
	else
		LLVM_CONFIG_BIN = llvm-config
	endif
else
	_ := $(foreach i,$(shell seq $(MIN_SUPPORT_MAJOR_VERSION) $(MAX_SUPPORT_MAJOR_VERSION)),$(call find_llvm_config_bin,$(i)))
	ifeq ($(LLVM_CONFIG_BIN),)
		LLVM_CONFIG_BIN = llvm-config
	endif
endif

VERSION = $(shell $(LLVM_CONFIG_BIN) --version)
MAJOR_VERSION = $(firstword $(subst ., ,$(VERSION)))

CONFIG_FILE = llvm_config.go

.PHONY: clean
clean:
	@rm -f $(CONFIG_FILE)

.PHONY: config
config: clean
	@echo "// Automatically generated by \`$(LLVM_CONFIG_BIN)\`, do not edit." >> $(CONFIG_FILE)
	@echo "" >> $(CONFIG_FILE)
	@echo "package main" >> $(CONFIG_FILE)
	@echo "" >> $(CONFIG_FILE)
	@echo "// #cgo CFLAGS: $(shell $(LLVM_CONFIG_BIN) --cflags)" >> $(CONFIG_FILE)
	@echo "// #cgo CXXFLAGS: $(subst -funwind-tables ,,$(shell $(LLVM_CONFIG_BIN) --cxxflags))" >> $(CONFIG_FILE)
	@echo "// #cgo LDFLAGS: -L$(shell $(LLVM_CONFIG_BIN) --libdir) $(shell $(LLVM_CONFIG_BIN) --libs)" >> $(CONFIG_FILE)
	@echo "import \"C\"" >> $(CONFIG_FILE)